package com.geek.novel.activity.comment

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.geek.novel.R
import com.geek.novel.activity.base.TitleBarActivity
import com.geek.novel.adapter.BookSearchListAdapter
import com.geek.novel.bo.AppContext
import com.geek.novel.common.Constant
import com.geek.novel.entity.BookRead
import com.geek.novel.network.RslHandler
import com.geek.novel.services.NovelService
import com.geek.novel.utils.LogCatUtil
import com.geek.novel.utils.ToastUtils
import com.geek.novel.view.loading.LoadingDialogUtil
import com.geek.novel.vo.ApiErrorResult
import com.geek.novel.vo.ApiResult
import com.geek.novel.vo.BookSearchVo
import com.geek.novel.vo.Pager
import kotlinx.android.synthetic.main.activity_book_category.*


class BookCommentActivity: TitleBarActivity() , RslHandler {

	/**书籍列表*/
	private var bookList: ArrayList<BookRead> = ArrayList()

	/**搜索的关键字*/
	private var category: String = ""

	/**书籍分类的文本*/
	private var categoryStr: String = ""

	/**当前页码，下标从0开始*/
	private var pageNo: Int = 0
	/**每页显示条数*/
	private var pageSize: Int = 10

	/**书籍列表的适配器*/
	private lateinit var categoryBookAdapter: BookSearchListAdapter

	/**小说服务*/
	private lateinit var novelService: NovelService

	override fun pageName(): String = AppContext.getContext().getString(R.string.title_bar_book_comment)
	
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_book_category)

		try {//设置背景为白色
			super.setBackgroundColor(Color.WHITE)

			//初始化服务对象
			novelService = NovelService(this)

			//获取分类信息
			this.initCategory()

			//初始化下拉刷新功能
			this.initRefreshLayout()

			//初始化列表
			this.initListView()

			//获取分类书籍数据
			this.queryBookByCategory()

		} catch (e: Exception) {
			ToastUtils.toast(e.message)
			finish()
		}

	}

	/**获取分类信息*/
	private fun initCategory(){
		val bundle = intent.extras?:Bundle()
		val str = bundle.getString("category")
		if(TextUtils.isEmpty(str)){
			throw Exception("书籍分类数据不能为空！")
		}
		this.category = str!!
	}

	/**获取分类书籍数据*/
	private fun queryBookByCategory() {
		LoadingDialogUtil.getInstance().showLoading("数据加载中...")
		//发起请求
		this.resetSearchBook()
		this.searchBook()
	}

	/**附加控件*/
	override fun attachViewChild() {
	}

	/**绑定事件*/
	override fun bindEventChild() {
	}

	/**重置搜索下标*/
	private fun resetSearchBook(){
		book_category_refresh_layout.resetNoMoreData()
		this.pageNo = 0
		this.bookList.clear()
	}

	/**搜索*/
	private fun searchBook(){
		novelService.queryBookByCategory(category, Pager.of(pageNo, pageSize))
		pageNo++
	}

	/**处理搜索结果*/
	private fun handleQueryResult(vo: BookSearchVo, view: View){
		try {
			val pager = vo.result ?: throw Exception("获取查询结果异常！")
			val records = pager.records ?: throw Exception("获取查询结果异常！")
			bookList.addAll(records)
			categoryBookAdapter.notifyDataSetChanged()

			this.checkBookEmpty(view)
		} catch (e: Exception) {
			ToastUtils.toast(e.message)
			LogCatUtil.e("???", e.message, e)
		}
	}

	/**检查书籍列表是否为空*/
	private fun checkBookEmpty(view: View): Boolean{
		//书架列表为空的情况，添加书籍按钮
		if(bookList.isEmpty()){
			view.visibility = View.VISIBLE
		}else{
			view.visibility = View.GONE
		}
		return bookList.isEmpty()
	}

	/**
	 * 初始化下拉刷新功能
	 */
	private fun initRefreshLayout(){
		book_category_refresh_layout.setRefreshHeader(book_category_classics_header)
		book_category_refresh_layout.setRefreshFooter(book_category_classics_footer)
		//下拉刷新
		book_category_refresh_layout.setOnRefreshListener {
			this.resetSearchBook()
			this.searchBook()
		}
		//滚动加载
		book_category_refresh_layout.setOnLoadMoreListener{
			this.searchBook()
		}
	}


	/**初始化列表*/
	private fun initListView(){
		//添加适配器
		categoryBookAdapter = BookSearchListAdapter(this, bookList)
		categoryBookAdapter.initListView(rv_category_books)
	}


	override fun onError(code: Int, err: ApiErrorResult) {
		when(code){
			//搜索结果
			Constant.HTTP_KEY_APP_GET_BOOK_BY_CATEGORY->{
				LoadingDialogUtil.getInstance().dismiss()
				book_category_refresh_layout.finishRefresh(false)
				book_category_refresh_layout.finishLoadMore(false)
			}
		}
	}

	override fun onSuccess(result: ApiResult, code: Int) {
		when(code){
			//搜索结果
			Constant.HTTP_KEY_APP_GET_BOOK_BY_CATEGORY->{
				LoadingDialogUtil.getInstance().dismiss()
				val bookSearchVo = result.getData() as BookSearchVo
				this.handleQueryResult(bookSearchVo, ly_book_category_no_result)
				//处理下拉刷新
				book_category_refresh_layout.finishRefresh(true)
				//处理滚动加载
				val noMoreData = bookSearchVo.result!!.totalPages-1 < pageNo
				book_category_refresh_layout.finishLoadMore(0, true, noMoreData)
			}
		}
	}

}